// pages/search/search.js
Page({
  data: {
    keyword: '',
    searchHistory: []
  },

  /**
   * 页面初始加载和返回回显搜索历史
   */
  onShow() {
    let searchHistory = wx.getStorageSync('searchHistory')
    console.log(this.data.searchHistory.length)
    if (!searchHistory) {
      this.setData({
        searchHistory: []
      })
      return
    }
    this.setData({
      searchHistory
    })
  },

  /**
   * 关键词输入，数据绑定
   * @param {*} e 
   */
  onChange(e) {
    this.setData({
      keyword: e.detail
    })
  },

  /**
   * 提交搜索
   */
  onSearch() {
    let searchHistory = this.data.searchHistory
    let keyword = this.data.keyword
    if (keyword == '') {
      return
    }
    // 搜索词不为空
    searchHistory.push(keyword)
    console.log(searchHistory)
    wx.setStorageSync('searchHistory', searchHistory)
    wx.navigateTo({
      url: `/pages/goodsList/goodsList?keyword=${this.data.keyword}&isCategory=0`
    })
  },

  /**
   * 清空搜索历史
   */
  clearHistory() {
    wx.removeStorageSync('searchHistory')
    this.setData({
      searchHistory: []
    })
  },


  /**
   * 点击取消返回上一页
   */
  onCancel() {
    wx.navigateBack({
      delta: 1,
    })
  }
})